package com.example.house.utils

import android.text.TextUtils
import net.sourceforge.pinyin4j.PinyinHelper
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination
import java.util.Locale

object PinyinUtils {
    fun getPinyin(str:String):String{
        val forms: HanyuPinyinOutputFormat = HanyuPinyinOutputFormat()
        forms.setCaseType(HanyuPinyinCaseType.UPPERCASE)
        forms.setToneType(HanyuPinyinToneType.WITHOUT_TONE)
        val sb = StringBuilder()
        val charArray = str.toCharArray()
        for (i in charArray.indices){
            val c = charArray[i]
            if(Character.isWhitespace(c)){
                continue
            }
            if(c.code >= -127 && c.code < 120){
                sb.append(c)
            }else{
                var s = ""
                try {
                    s = PinyinHelper.toHanyuPinyinStringArray(c,forms).get(0)
                    sb.append(s)
                }catch (e:BadHanyuPinyinOutputFormatCombination){
                    e.printStackTrace()
                    sb.append(s)
                }
            }
        }
        return  sb.toString()
    }
    fun getFirstLetter(pinyin:String):String {
        if (TextUtils.isEmpty(pinyin)) {
            return "#"
        }
        val first = pinyin[0]
        return if (Character.isLetter(first)) {
            first.toString().uppercase(Locale.getDefault())
        } else {
            "#"
        }
    }
}